<?php

namespace App\Http\Controllers;

use App\Models\Phone;
use App\Models\PhoneSetting;
use App\Models\SipUser;
use App\Models\SmsSetting;
use App\Services\PlivoService;
use App\Services\TwilioService;
use App\Transformers\PhoneSettingTransformer;
use App\Transformers\SmsSettingTransformer;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;

class SettingController extends Controller
{
    /**
     * @api {post} /api/phone/setting 电话配置添加
     * @apiGroup Setting
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {String} type  twilio或者plivo
     * @apiParam {String} account
     * @apiParam {String} auth_token
     * @apiParam {String} alias  自定义名
     * @apiParam {String} site  节点id
     *
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 201 OK
     *
     */
    public function phoneSetting(Request $request, TwilioService $twilioService, Phone $phone){

        $validatedData = $request->validate([
            'type' => [
                'required',
                Rule::in(['twilio', 'plivo', 'sip']),
            ],
            'account' => 'required|unique:phone_settings',
            'auth_token'=>'required|unique:phone_settings',
            'alias'=>'required|unique:phone_settings',
            'site'=>'nullable'
        ],[],[
        ]);

        $res = PhoneSetting::where('status',1)->get()->toArray();
        if(!$res){
            $validatedData['status'] = 1;
        }

        if($validatedData['type'] == 'twilio'){
            //获取此配置电话列表
            $list = $twilioService->numberList($validatedData['account'],$validatedData['auth_token']);
            if(isset($list['status'])&&$list['status'] == 422){
                return response()->json($list, 422);
            }
            $phone_ssetting = PhoneSetting::create($validatedData);
            //更新电话表数据库
            $phone->updateSettingPhone($list, $phone_ssetting->id);
        }elseif ($validatedData['type'] == 'plivo'){
            $phone_ssetting = PhoneSetting::create($validatedData);
        }elseif ($validatedData['type'] == 'sip'){
            //判断SIPUSER表中账号密码是否一致
            $res = SipUser::where('sip',$validatedData['account'])->first();
            if($res){
                if($res->pass == $validatedData['auth_token']){
                    $validatedData['balance'] = $res->balance;
                    $phone_ssetting = PhoneSetting::create($validatedData);
                }else{
                    return response()->json(['error' => '账号错误或密码错误'], 422);
                }
            }else{
                return response()->json(['error' => '账号错误或密码错误'], 422);
            }
        }

        return $this->response->item($phone_ssetting, new PhoneSettingTransformer());
    }

    /**
     * @api {get} /api/phone/setting 电话配置列表
     * @apiGroup Setting
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     *       {
     *           "data": [
     *               {
     *                   "id": 1,
     *                   "type": "twilio",
     *                   "account": "xxxxxxxxxxxxxxxxxx",
     *                   "auth_token": "aaaaaaaaaaaaaaaaa",
     *                   "site": "au",
     *                   "alias": "twilio-1",
     *                   "created_at": "2018-12-28 16:25:20",
     *                   "updated_at": "2018-12-28 16:25:20"
     *               },
     *            ]
     *        }
     *
     */
    public function phoneIndex(){
        $data = PhoneSetting::all();

        return $this->response->collection($data, new PhoneSettingTransformer());
    }

    /**
     * @api {delete} /api/phone/setting/:id 电话配置删除
     * @apiGroup Setting
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} id  url传参
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 204 OK
     *
     */
    public function phoneDestroy(PhoneSetting $phoneSetting){
        $phoneSetting->delete();

        return $this->response->noContent();
    }

    /**
     * @api {get} /api/phone/setting/status/:id 电话配置启用
     * @apiGroup Setting
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} id  url传参
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 204 OK
     *
     */
    public function phoneStatus(PhoneSetting $phoneSetting){
        $phoneSetting->status = 1;
        $phoneSetting->save();
        PhoneSetting::where('id','<>',$phoneSetting->id)->orderBy('id')->chunk(100, function ($settings) {
            foreach ($settings as $setting) {
                $setting->status = 0;
                $setting->save();
            }
        });
        return $this->response->item($phoneSetting, new PhoneSettingTransformer());
    }

    /**
     * @api {get} /api/setting/sync/:phoneSetting 电话配置同步
     * @apiGroup Setting
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} id  url传参
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 204 OK
     *
     */
    public function sync(PhoneSetting $phoneSetting,TwilioService $twilioService, Phone $phone,PlivoService $plivoService, SipUser $sipUser){
        if($phoneSetting->type == 'twilio'){
            //获取服务下的所有电话号码
            $list = $twilioService->numberList($phoneSetting->account, $phoneSetting->auth_token);
            if(isset($list['status'])&& $list['status']==422){
                return response()->json(['error' => '同步数据有误'], 422);
            }
            //同步数据库
            $phone->updateSettingPhone($list,$phoneSetting->id);
        }elseif ($phoneSetting->type == 'plivo'){
            $list = $plivoService->phoneList();
            if($list){
                //同步数据库
                $phone->updateSettingPhone($list,$phoneSetting->id);
            }else{
                return response()->json(['message' => '获取电话列表失败']);
            }
        }elseif ($phoneSetting->type == 'sip'){
            //取出sip的电话号码（这里是账号跟密码）
            $res = $sipUser->where([
                ['sip','=',$phoneSetting->account],
                ['pass','=',$phoneSetting->auth_token]
            ])->first();
            if($res){
                //配置下的所有电话号码
                $list = $sipUser->where('proxy_id',$res->id)->select('sip','pass')->get()->toArray();
                //同步数据库
                $phone->updateSettingPhoneSip($list,$phoneSetting->id);
            }else{
                return response()->json(['message' => '获取电话列表失败']);
            }
        }
        return response()->json(['message' => '同步完成']);
    }

    /**
     * @api {patch} /api/phone/setting/:id 电话配置站点修改
     * @apiGroup Setting
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} id  url传参
     * @apiParam {string} site  站点值
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 204 OK
     *
     */
    public function phoneSiteUpdate(PhoneSetting $phoneSetting,Request $request){
        $site = $request->only('site');
        $phoneSetting->update($site);
        return $this->response->item($phoneSetting, new PhoneSettingTransformer());
    }

    /**
     * @api {get} /api/phone/balance/:id 电话配置余额同步
     * @apiGroup Setting
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} id  url传参
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 204 OK
     * {
     *       "message": "同步余额成功"
     * }
     */
    public function phoneBalanceSync(PhoneSetting $phoneSetting){
        if($phoneSetting->type == 'sip'){
            $res = SipUser::where([
                ['sip','=',$phoneSetting->account],
                ['pass','=',$phoneSetting->auth_token]
            ])->first();
            if($res){
                $phoneSetting->update([
                    'balance' => $res->balance
                ]);
            }
        }
        return response()->json(['message' => '同步余额成功']);
    }


    /**
     * @api {post} /api/sms/setting 短信配置添加
     * @apiGroup Setting
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {String} alias  名称
     * @apiParam {String} value  内容
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 204 OK
     *
     */
    public function SmsSetting(Request $request,SmsSetting $smsSetting){
        $validatedData = $request->validate([
            'value' => 'required',
            'alias'=>'required',
        ],[],[
        ]);
        $res = SmsSetting::where('status',1)->get()->toArray();
        if(!$res){
            $validatedData['status'] = 1;
        }
        $smsSetting->create($validatedData);
        return $this->response->created();
    }
    /**
     * @api {patch} /api/sms/setting/:id 短信配置修改
     * @apiGroup Setting
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} id  url传参
     * @apiParam {String} alias  配置名称
     * @apiParam {String} value  短信配置值
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 204 OK
     *
     *           {
     *               "id": 5,
     *               "type": null,
     *               "value": "http://35.236.142.246",
     *               "auth_token": null,
     *               "status": 0,
     *               "alias": "sms配置",
     *               "created_at": "2019-01-18 21:24:13",
     *               "updated_at": "2019-01-18 21:39:56"
     *           }
     */
    public function SmsSiteUpdate(SmsSetting $smsSetting,Request $request){
        $smsSetting->update($request->only('alias','value'));
        return $this->response->item($smsSetting, new SmsSettingTransformer());
    }

    /**
     * @api {get} /api/sms/setting/:id 短信配置状态修改
     * @apiGroup Setting
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} id  url传参
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 204 OK
     *           {
     *               "id": 1,
     *               "type": null,
     *               "value": "http://35.236.142.246",
     *               "status": 1,
     *               "alias": "短信配置1",
     *               "created_at": "2019-01-18 21:17:54",
     *               "updated_at": "2019-01-21 14:07:12"
     *           }
     *
     */
    public function SmsStatus(SmsSetting $smsSetting){
        $smsSetting->status = 1;
        $smsSetting->save();
        SmsSetting::where('id','<>',$smsSetting->id)->orderBy('id')->chunk(100, function ($settings) {
            foreach ($settings as $setting) {
                $setting->status = 0;
                $setting->save();
            }
        });
        return $this->response->item($smsSetting, new SmsSettingTransformer());
    }

    /**
     * @api {delete} /api/sms/setting/:id 短信配置删除
     * @apiGroup Setting
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} id  url传参
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 204 OK
     *
     */
    public function SmsDestroy(SmsSetting $smsSetting){
        $smsSetting->delete();

        return $this->response->noContent();
    }

    /**
     * @api {get} /api/sms/setting 短信配置列表
     * @apiGroup Setting
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     *       {
     *           "data": [
     *               {
     *                   "id": 1,
     *                   "type": "twilio",
     *                   "account": "xxxxxxxxxxxxxxxxxx",
     *                   "auth_token": "aaaaaaaaaaaaaaaaa",
     *                   "site": "au",
     *                   "alias": "twilio-1",
     *                   "created_at": "2018-12-28 16:25:20",
     *                   "updated_at": "2018-12-28 16:25:20"
     *               },
     *            ]
     *        }
     *
     */
    public function smsIndex(){
        $data = SmsSetting::all();
        return $this->response->collection($data, new SmsSettingTransformer());
    }
}
